#推荐2

import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity

# 读取CSV数据集
df = pd.read_csv('M_U.csv')
df = df.dropna(subset=['Star_count'])  # 去除Star_count为空的记录
df['Star_count'] = df['Star_count'].astype(float)

# 创建一个用户-电影评分矩阵
#pivot_table = df.pivot(index='Uid', columns='Movie_id', values='Star_count').fillna(0)
pivot_table = df.groupby(['Uid', 'Movie_id'])['Star_count'].max().unstack(fill_value=0)
# 计算用户之间的余弦相似度
user_similarity = cosine_similarity(pivot_table)

# 定义一个函数来找到相似用户并推荐电影
def recommend_movies_to_user(user_id, liked_movies, pivot_table, user_similarity, n_recommendations=5):
    # 确保输入的用户ID存在于数据集中
    if user_id not in pivot_table.index:
        raise ValueError(f"User ID {user_id} not found in the dataset.")
        # 获取输入用户喜欢的电影的评分
    user_ratings = pivot_table.loc[user_id]
    # 初始化一个字典来存储每部电影的相似用户评分总和
    movie_scores = {}
    # 遍历所有用户，找到喜欢相同电影的用户
    for other_user_index, other_user_similarity in enumerate(user_similarity[pivot_table.index.get_loc(user_id)]):
        if other_user_index == pivot_table.index.get_loc(user_id):  # 跳过自己
            continue

        other_user_ratings = pivot_table.iloc[other_user_index]

        # 检查其他用户是否喜欢输入用户喜欢的电影
        for movie_id in liked_movies:
            if other_user_ratings[movie_id] > 0:  # 如果喜欢
                # 累加该用户对其他电影的评分到movie_scores中
                for movie_id_other, rating in other_user_ratings.items():
                    if movie_id_other not in liked_movies and rating > 0:
                        movie_scores[movie_id_other] = movie_scores.get(movie_id_other,
                                                                        0) + other_user_similarity * rating
                        # 对电影评分进行排序，取前n个推荐
    sorted_scores = sorted(movie_scores.items(), key=lambda x: x[1], reverse=True)
    recommended_movies = [movie_id for movie_id, _ in sorted_scores[:n_recommendations]]

    return recommended_movies


# 示例：为用户id=99推荐电影，该用户喜欢电影id为[1291543, 1291545, 1291546]
user_id = 7  # 假设用户99不在数据集中，但我们仍然可以基于其他用户的喜好来推荐
liked_movies = [1291543, 1291545, 1291546]

recommended_movies = recommend_movies_to_user(user_id, liked_movies, pivot_table, user_similarity)
print(f"Recommended Movies for User {user_id}: {recommended_movies}")
print("推荐给用户的电影列表:")
movid_title=[]
for movie_id in recommended_movies:
    movie_title = df.loc[df['Movie_id'] == movie_id, 'Title'].values[0]
    movid_title.append(movie_title)
print(movid_title)
    #print(f"电影ID: {movie_id}, 电影名称: {movie_title}")